import { App, ComponentOptions } from 'vue';

export default function addComponents(app: App) {
  const componentList = import.meta.globEager('../components/**/index.vue');
  // console.log(componentList);
  const pathList = Object.keys(componentList);
  if (pathList.length === 0) return;
  const list = pathList.map((key) => {
    const tmpl = key.match(/\/Template\w+/);
    if (tmpl && tmpl[0]) {
      return componentList[key].default;
    }
  });
  // console.log(list);
  const customComponents = formatComponentName(list);

  customComponents.forEach((c) => {
    app.component(c.name, c.component);
  });
}

function formatComponentName(component: ComponentOptions[]) {
  if (component.length === 0) return [];
  return component.map((item) => ({
    name: splitComponentName(item.name as string),
    component: item
  }));
}

function splitComponentName(name: string) {
  return name.replace(/([A-Z])/g, (_, $1: string) => `-${$1.toLowerCase()}`).slice(1);
}
